<?php

namespace App\Http\Middleware;

use App\Models\User;
use App\Models\UserConnect;
use App\Models\UserGroup;
use App\WeChat\WxApi\WxJsApi;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class WeixinAuth
{
    /**
     * @param $request
     * @param Closure $next
     * @return mixed
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function handle(Request $request, Closure $next)
    {
        if (!Auth::check()) {
            if ($request->has('code') && $request->has('state')) {
                try{
                    $code = $request->input('code');
                    $state = $request->input('state');
                    $user = WxJsApi::getUserinfoWithCode($code);
                    $connect = UserConnect::where('openid', $user->openid())->first();
                    if ($connect) {
                        if ($connect->user) {
                            Auth::loginUsingId($connect->uid);
                            Auth::user()->update(['username'=>$user->nickname()]);
                            $connect->update([
                                'nickname'=>$user->nickname(),
                                'gender'=>$user->sex(),
                                'city'=>$user->city(),
                                'province'=>$user->province(),
                                'country'=>$user->country(),
                                'avatar'=>$user->headimgurl(),
                                'updated_at'=>time()
                            ]);
                        } else {
                            $connect->delete();
                            $this->RegisterUser($request, $user);
                        }
                    } else {
                        $this->RegisterUser($request, $user);
                    }
                    //同步头像
                    WxJsApi::syncHeadImg(Auth::id(), $user->headimgurl());

                    return redirect(url()->current());
                }catch (\Exception $e) {
                    return response()->json($e);
                }
            } else {
                return redirect(WxJsApi::createOauthUrlForCode(url()->current()));
            }
        }
        return $next($request);
    }

    private function RegisterUser(Request $request, SnsUserinfo $info)
    {
        $request->offsetSet('src', 'weixin');
        $user = User::create([
            'username'=>$info->nickname(),
            'password'=>Hash::make(''),
            'created_at'=>time(),
            'gid'=>UserGroup::userGroups()->first()->gid
        ]);

        if ($user) {
            $user->connect()->create([
                'platform'=>'weixin',
                'openid'=>$info->openid(),
                'nickname'=>$info->nickname(),
                'gender'=>$info->sex(),
                'city'=>$info->city(),
                'province'=>$info->province(),
                'country'=>$info->country(),
                'avatar'=>$info->headimgurl(),
                'created_at'=>time()
            ]);
        }

        Auth::loginUsingId($user->uid);
    }
}
